package com.bwie.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbCustomer;
import com.bwie.service.TbCustomerService;
import com.bwie.mapper.TbCustomerMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author lenovo
 * @description 针对表【tb_customer(客户表)】的数据库操作Service实现
 * @createDate 2025-07-11 10:44:32
 */
@Service
public class TbCustomerServiceImpl extends ServiceImpl<TbCustomerMapper, TbCustomer>
        implements TbCustomerService {


    @Autowired
    TbCustomerMapper tbCustomerMapper;


    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public R sendCode(String phone) {

        //生成随机的验证码
        String code = RandomUtil.randomNumbers(4);
        //发送验证码
        MobileMessageUtil.sendMobileMessage(phone, code);
        //打印验证码
        System.out.println("验证码为：" + code);
        //保存验证码
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

        return R.OK(code);
    }

    @Override
    public R loginPhone(LoginVo loginVo) {

        if (!Validator.isMobile(loginVo.getPhone())) {
            return R.ERROR(500, "手机号格式不正确");
        }

        String redisCode = redisTemplate.opsForValue().get(loginVo.getPhone());
        if (redisCode == null) {
            return R.ERROR(500, "验证码不存在");
        }

        TbCustomer tbCustomer = tbCustomerMapper.selectOne(
                new QueryWrapper<TbCustomer>().lambda().eq(TbCustomer::getPhone, loginVo.getPhone())
        );
        if (tbCustomer == null) {
            return R.ERROR(500, "用户不存在");
        }
        if (!redisCode.equals(loginVo.getCode())) {
            return R.ERROR(500, "验证码错误");
        }

        //生成token并存储
        String tokenKey = "token-" + tbCustomer.getCustomerId();
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("customerId", tbCustomer.getCustomerId())
                .claim("phone", tbCustomer.getPhone())
                .compact();
        redisTemplate.opsForValue().set(tokenKey, token, 5, TimeUnit.MINUTES);

        tbCustomer.setPassword(null);
        tbCustomer.setToken(token);

        return R.OK(tbCustomer);
    }
}




